<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    :bodyStyle="bodyStyle"
    wrapClassName="ant-modal-cust-warp"
    style="top:15%;height: 70%;overflow-y: hidden"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <!-- <a-col :span="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报价记录表ID">
            <a-input disabled v-decorator.trim="['recordId']" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="报价日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-date-picker
              style="width: 100%"
              v-decorator.trim="['quotationDate', validatorRules.required]"
              format="YYYY-MM-DD"
              placeholder="请输入报价日期"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="报价表上传">
            <a-upload
              name="file"
              accept=".txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
              :beforeUpload="beforeUpload"
              :multiple="false"
              :headers="tokenHeader"
              :action="importExcelUrl"
              :showUploadList="false"
              @change="myhandleImportExcel"
            >
              <a-button> <a-icon type="upload" />上传</a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { AddQuotation, checkSupplier } from '@/api/api'
import { autoJumpNextInput } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: 'addQuotationList',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      model: {},
      record: null,
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.5 + 'px',
        'overflow-y': 'auto'
      },
      isReadOnly: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      defaultFileList: null,
      url: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=jlb`,
        exportXlsUrl: '/systemConfig/static'
      },
      form: this.$form.createForm(this),
      validatorRules: {
        required: {
          rules: [{ required: true, message: '请输入' }]
        }
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
    }
  },
  created() {},
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        //文件名后缀
        let hz = file.name.substring(file.name.lastIndexOf('.'))
        let isType = ['.xlsx', '.doc', '.txt', '.docx', '.xls', '.ppt', '.pptx', '.pdf'].includes(hz)
        if (!isType) {
          this.$message.error('格式错误,只能上传.xlsx、.doc、.txt、.docx、.xls、.ppt、.pptx、.pdf')
          return reject(false)
        }
        return resolve(true)
      })
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
            console.log('defaultFileList:', this.defaultFileList)
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    add(record) {
      this.record = record
      this.edit(record)
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        //编辑
        if (!record.productName) {
          var quotationDate = this.$moment(this.model.quotationDate)
          this.form.setFieldsValue({ quotationDate: quotationDate })
        }
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          //recordID存在则为编辑模式
          if (this.model.recordId) {
            formData.recordId = this.model.recordId
            formData.id = this.model.id
          } else {
            formData.recordId = this.model.id
          }
          if (this.defaultFileList) {
            formData.quotationForm = this.defaultFileList
          } else {
            formData.quotationForm = this.model.quotationForm
          }
          formData.quotationDate = this.$moment(formData.quotationDate).format('YYYY-MM-DD')
          let obj
          if (!this.model.id) {
            obj = AddQuotation(formData)
          } else {
            obj = AddQuotation(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
